import { Directive, ElementRef, HostListener, Input, OnChanges, TemplateRef, ViewContainerRef } from '@angular/core';

//自定义结构指令,允许根据某些条件操纵 DOM 的结构
@Directive({
  selector: '[libCustomShow]',
  standalone: true
})
export class CustomShowDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) { }

  @Input() set libCustomShow(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

}



//自定义属性指令可以响应宿主元素上的更改或处理事件。
@Directive({
  selector: '[libCustomAttribute]',
  standalone: true

})
export class CustomAttributeDirective {
  constructor(private elementRef: ElementRef) { }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
    this.elementRef.nativeElement.style.cursor = 'pointer';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string | null) {
    this.elementRef.nativeElement.style.backgroundColor = color;
  }
}


//指令可以使用 HostListener 响应用户启动的事件。
@Directive({
  selector: '[libCustomClickEvent]',
  standalone: true
})
export class CustomClickEventDirective implements OnChanges {
  constructor(private elementRef: ElementRef) { }

  @Input() rawClick?: (inputData: any) => void;

  @Input() rawData: any;
  @HostListener('click', ['$event']) onClick(event: MouseEvent) {
    console.log('Element clicked', { event, rawData: this.rawData });
    this.rawClick && this.rawClick({
      ...this.rawData,
      flag: 'click'
    });
  }

  ngOnChanges() {
    console.log('ngOnChanges', this.rawData, this.elementRef);
    this.elementRef.nativeElement.innerText = this.rawData.name;
  }
}